package com.bhf.security;

import com.alibaba.fastjson.JSON;
import com.bhf.constant.ResultCodeEnum;
import com.bhf.utils.RestResultUtils;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author pwq
 */
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(RestResultUtils.buildResult(ResultCodeEnum.AUTHENTICATION_IS_REQUIRED,e.getMessage())));
        out.flush();
        out.close();
    }
}
